package com.controller;

import java.io.Serializable;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import com.Util.FacesUtils;
import com.facade.UserFacade;
import com.model.User;

@SuppressWarnings("serial")
@ManagedBean
@SessionScoped
public class LoginController implements Serializable {

	@EJB
	private UserFacade userFacade;
	private User user;


	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	private String login;
	private String password;
	private String home = "/pages/public/login.xhtml?faces-redirect=true";

	public String getHome() {
		return home;
	}

	public String loginAction() {
		user = userFacade.findUserByLogin(login);
		if (user != null) {
			if (password.equals(user.getPassword())) {
				user.setIsConnected(true);
				userFacade.updateUser(user);
				this.setUser(user);
			} else {
				String msg = "Password Incorrect";
				FacesUtils.addErrorMessage(msg);
				return null;
			}
		} else {
			String msg = "Login Incorrect";
			FacesUtils.addErrorMessage(msg);
			return null;
		}		
		if (user.getRole().equals("Administrator")) {
			home = "/pages/protected/admin/adminUser.xhtml?faces-redirect=true";					
		}else		
		home = "/pages/protected/user/simpleUser.xhtml?faces-redirect=true";
		return home;
	}
	
	public String disconnect(){		
		user.setIsConnected(false);
		userFacade.updateUser(user);
		this.setUser(null);
		home = "/pages/public/login.xhtml?faces-redirect=true";
		return home;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
